package cn.lingxue.lingapi.utils;

import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Random;

/**
 * MD5工具类
 *
 * @author 多仔ヾ
 */
public class MD5Util {

    private static MessageDigest messageDigest = null;
    private static final char[] hexDigits = {'8', '9', '7', '4', '5', '0', '2', '6', '3', '1', 'C', 'D', 'A', 'B', 'E', 'F'};
    private static final char[] hexDigits2 = { '0', '1', '2', '3', '4', '5', '6','7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' };

    private static MessageDigest getMessageDigest() {
        if (messageDigest == null) {
            try {
                messageDigest = MessageDigest.getInstance("MD5");
            } catch (NoSuchAlgorithmException e) {
                e.printStackTrace();
            }
        }
        return messageDigest;
    }

    /**
     * MD5普通加密
     *
     * @author 多仔ヾ
     * @param inStr 待加密字符串
     * @return 加密结果
     **/
    public static String encode(String inStr) {
        try {
            byte[] btInput = inStr.getBytes(StandardCharsets.UTF_8);
            getMessageDigest().update(btInput);
            byte[] md = getMessageDigest().digest();
            int j = md.length;
            char[] str = new char[j * 2];
            int k = 0;
            for (byte byte0 : md) {
                str[k++] = hexDigits2[byte0 >>> 4 & 0xf];
                str[k++] = hexDigits2[byte0 & 0xf];
            }
            return new String(str);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * MD5盐值加密
     *
     * @author 多仔ヾ
     * @param inStr 待加密字符串
     * @param salts 盐值
     * @return 加密结果
     **/
    public static String encode(String inStr, String salts) {
        return encode(salts + inStr + salts);
    }

    /**
     * 生成随机盐值
     *
     * @author 多仔ヾ
     * @param length 盐值长度
     * @return 盐值
     **/
    public static String randSalts(int length) {
        Random r = new Random();
        StringBuilder sb = new StringBuilder();
        String vars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
        for(int i = 0; i < length; i++){
            int n = r.nextInt(vars.length());
            sb.append(vars.charAt(n));
        }
        return sb.toString();
    }

}